<template>
	<view class="content">
		<view class="app-title ac">
			<view class="fl" @click="back">
				<image class="back" src="/static/img/back.png"></image>
			</view>
			<view class="title">数据下载</view>
		</view>
		<view class="content-download">
			<view class="content-title">请选择需要下载的表数据</view>
			<view class="content-search">
				<view>
					<u-cell-item class="cell-major" title="专业:" :value="searchForm.majorName || '请选择'"
						@click="showData('major')" />
					<ba-tree-picker ref="treePickermajor" title="" :localdata="workProfession" valueKey="code" textKey="value"
						childrenKey="children" :multiple="true" :selectedData="searchForm.selectedMajor" @select-change="
				      (codeArr, names) => changeSelectTree(codeArr, names, 'major')
				    " />
				</view>
				<u-cell-item title="开始时间:" :value="searchForm.startTime || '请选择'" @click="
				    show_date = true;
				    date_type = 'startTime';
				  ">
				</u-cell-item>
				<u-cell-item title="结束时间:" :value="searchForm.endTime || '请选择'" @click="
				    show_date = true;
				    date_type = 'endTime';
				  ">
				</u-cell-item>
			</view>
			<view v-show="false" class="check-btn">
				<u-button :custom-style="customStyle" type="primary" size="medium" @click="handleCheck(1)">
					全选
				</u-button>
				<u-button :custom-style="customStyle" type="primary" size="medium" @click="handleCheck(2)">
					反选
				</u-button>
			</view>
			<view v-show="false" class="content-list">
				<view v-for="(item, index) in dataList" :key="index">
					<u-checkbox v-model="item.checked" v-if="item.name" :name="item.name"
						@change="(val) => checkChange(val, item)">{{item.name}}</u-checkbox>
				</view>
			</view>
			<view class="download-btn">
				<u-button :custom-style="customStyle" type="primary" size="medium" @click="handleDownload">
					下载
				</u-button>
				<u-button :custom-style="customStyle" type="primary" size="medium" @click="handleCancel">
					取消
				</u-button>
			</view>
		</view>
		<u-picker v-model="show_date" mode="time" :params="timeParams" @confirm="setDate" @cancel="onCancel"></u-picker>
		<!-- <web-view v-if="webSrc" :src="webSrc" :webview-styles="webviewStyles" @message="postMessage"></web-view> -->
	</view>
</template>
<script>
	import dayjs from "../../static/plugins/js/dayjs/dayjs.min.js";
	import {
		SYS_APP_CONTROLLER
	} from "../../api/sys";
	import {
		mapState
	} from "vuex";

	var wv; // 计划创建的webview
	var currentWebview;
	const info = uni.getSystemInfoSync();
	export default {
		data() {
			return {
				searchForm: {
					startTime: "",
					endTime: "",
					majorName: "",
					majorCode: "",
					selectedMajor: [],
				},
				show_date: false,
				timeParams: {
					year: true,
					month: true,
					day: true,
					hour: true,
					minute: true,
					second: true,
				},
				customStyle: {
					// backgroundColor: "#15c6ac",
					width: "20%",
				},
				dataList: [],
				webviewStyles: {
					// width: 0
					top: "10000"
				},
				webSrc: "",
			};
		},
		computed: {
			...mapState(["workProfession"]),
		},
		onReady() {
			setTimeout(() => {
				// 获取当前页面的webview对象
				// this.getWebView(currentWebview); // 如果是页面初始化调用时，需要延时一下
			}, 1500);
		},
		mounted() {
			this.searchForm.startTime = dayjs().subtract(3, 'day').startOf('day').format("YYYY-MM-DD HH:mm:ss");
			this.searchForm.endTime = dayjs().endOf('day').format("YYYY-MM-DD HH:mm:ss");
			this.$nextTick(() => {
				this.getData();
			})
		},
		methods: {
			getWebView() {
				currentWebview = this.$scope.$getAppWebview();
				setTimeout(function() {
					wv = currentWebview.children()[0];
					wv && wv.setStyle({
						scalable: true,
						top: "1000",
						height: 0,
						width: 0,
					});
				}, 500);
				// #ifdef APP-PLUS
				// #endif
			},
			postMessage(data) {
				console.log(data);
				this.webSrc = "";
			},
			async handleDownload() {
				if (!this.searchForm.majorName) {
					uni.showToast({
						title: "请先选择专业",
						icon: "none",
					});
					return false;
				}
				let list = this.dataList.filter((item) => item.checked);
				// this.webSrc = "/hybrid/html/download.html";
				// this.getWebView();
				// let self  = this;
				// setTimeout(function() {   
				// 	let data = {
				// 		list,
				// 		form: self.searchForm,
				// 		url: self.$store.state.baseUrl + SYS_APP_CONTROLLER.APP_DOWNLOAD_SQL
				// 	}
				// 	wv.evalJS(`download(${JSON.stringify(data)})`);
				// }, 1000);
				// return;
				if (!list.length) {
					uni.showToast({
						// title: "请先选择需要下载的文件",
						title: "当前专业未配置可下载的数据",
						icon: "none",
					});
					return false;
				}
				uni.showLoading({
					title: "下载中"
				});
				let fileList = [];
				// for (var i = 0; i < list.length; i++) {
					// let params = {
					// 	tableNameC: list[i].tableNameC || "",
					// 	tableNameE: list[i].tableNameE || "",
					// 	stratTimeName: list[i].stratTimeName || "",
					// 	endTimeName: list[i].endTimeName || "",
					// 	startTime: this.searchForm.startTime,
					// 	endTime: this.searchForm.endTime,
					// }
					let params = list.map((item) => {
						return {
							tableNameC: item.tableNameC || "",
							tableNameE: item.tableNameE || "",
							startTimeName: item.startTimeName || "",
							endTimeName: item.endTimeName || "",
							startTime: this.searchForm.startTime,
							endTime: this.searchForm.endTime,
						}
					})
					this.fetch(
						"post",
						this.$store.state.baseUrl + SYS_APP_CONTROLLER.APP_DOWNLOAD_SQL_STRING,
						params,
						false,
						false,
						false,
					).then((res) => {
						// const contentDisposition = res && res.header && res.header["content-disposition"] || res.header["Content-Disposition"] || "";
						// if (contentDisposition) {
						// 	let arr = contentDisposition.split(";")
						// 	let nameArr = arr.length && arr[2].split("=");
						// 	let name = nameArr[1] && decodeURIComponent(nameArr[1]);
						// 	name = name.replace(/^"|"$/g, '');
						// 	this.saveFile(name, res.data);
						// } else {
						// 	uni.showToast({
						// 		title: "缺少contentDisposition",
						// 		icon: "none",
						// 	});
						// }
						//  && typeof res.data == "string"
						if (res.data) {
							let date = dayjs().format("YYYY-MM-DD HH:mm:ss");
							// fileList.push({
							// 	fileName: `${list[i].tableNameC}-${date}.sql`,
							// 	fileData: res.data,
							// });
							this.saveFile(`${this.searchForm.majorName}-${date}.sql`, res.data);
						} else {
							uni.showToast({ title: "没有数据", icon: "none" });
						}
					}).catch((err) => {
						console.log(err);
						this.fail();
					}).finally(() => {
						uni.hideLoading();
					})
				// }
				// fileList.forEach((item) => {
				// 	this.saveFile(item.fileName, item.fileData);
				// })
			},
			saveFile(fileName, fileInfo, callback) {
				// 请求本地文件系统对象
				let path = "data/" + fileName;
				plus.io.requestFileSystem(
					plus.io.PUBLIC_DOWNLOADS, // 文件系统中的根目录
					(entry) => {
						// 文件在手机中的路径
						try {
							entry.root.getFile(
								path, {
									create: true
								},
								(fileEntry) => {
									fileEntry.createWriter((writer) => {
										// 写入文件成功完成的回调函数
										writer.onwrite = (e) => {
											this.success();
										};
										// 写入数据
										// writer.writeAsBinary(fileInfo);
										writer.write(fileInfo);
									});
								},
								(e) => {
									console.log(e);
									this.fail();
								}
							);
						} catch (error) {
							console.log(error);
							this.fail();
						}
					},
					(e) => {
						console.log(e);
						this.fail();
					}
				);
			},
			success() {
				uni.showToast({
					title: "下载成功",
					icon: "none",
				});
			},
			fail() {
				uni.showToast({
					title: "下载失败",
					icon: "none",
				});
			},
			getData() {
				this.dataList = [];
				// this.dataList = this.dataList.map((item) => {
				// 	return {
				// 		...item,
				// 		name: item.tableNameC,
				// 	}
				// });
				let params = {
					majors: this.searchForm.majorCode,
				}
				this.fetch(
					"get",
					this.$store.state.baseUrl + SYS_APP_CONTROLLER.APP_QUERY_SQL_TABLE,
					params,
				).then((res) => {
					if (res.returnCode == 2004) {
						this.dataList = res.data?.map((item, index) => {
							return {
								...item,
								index: index,
								name: item.tableNameC,
								checked: false,
							}
						}) || [];
						if (this.dataList.length) this.handleCheck(1);
					}
				})
			},
			handleCheck(type) {
				if (type == 1) {
					this.dataList.map(item => {
						item.checked = true;
					})
				} else if (type == 2) {
					this.dataList.map(item => {
						item.checked = !item.checked;
					})
				}
			},
			checkChange(val, item) {
				// this.dataList.map((it, index) => {
				// 	if (item.index == index) it.checked = val.value;
				// })
				this.dataList[item.index].checked = val.value;
			},
			handleCancel() {
				this.searchForm = {
					startTime: "",
					endTime: "",
				}
				this.dataList.map(item => {
					item.checked = false;
				})
			},
			setDate(obj) {
				let str = `${obj.year}-${obj.month}-${obj.day} ${obj.hour}:${obj.minute}:${obj.second}`;
				this.searchForm[this.date_type] = str;
				this.onCancel();
			},
			showData(type) {
				if (type == "major") {
					this.$refs[`treePicker${type}`]._show();
				}
			},
			changeSelectTree(idArr, nameStr, type) {
				let data = {
					id: (idArr && idArr.join(",")) || "",
					label: nameStr || "",
					selectedId: idArr,
				};
				this.changeSelect(data, type);
			},
			changeSelect(val, type) {
				console.log(val, type, "changeSelect");
				if (!val) return false;
				if (type == "major") {
					this.searchForm.majorName = val.label;
					this.searchForm.majorCode = val.id;
					this.searchForm.selectedMajor = val.selectedId;
					this.getData();
				}
			},
			onCancel() {
				this.show_date = false;
			},
			back() {
				uni.navigateTo({
					url: "/pages/index/index",
				});
			},
		},
		destroyed() {},
	};
</script>
<style scoped lang="less">
	.content {
		height: 100vh;
		position: fixed;
		width: 100%;
		background: #fff;

		.ac {
			display: flex;
			flex-direction: row;
			justify-content: space-between;
		}

		.app-title {
			.icon-select {
				width: 15px;
				height: 15px;
				margin-left: 5px;
				vertical-align: middle;
			}

			.title {
				width: 100%;
			}
		}

		.content-download {
			padding: 0 10px;

			.content-title {
				margin-top: 10px;
				font-size: 16px;
			}

			.content-search {
				margin-top: 20px;

				/deep/ .cell-major {
					.u-cell__value {
						height: 28px;
					}
				}
			}

			.check-btn {
				margin-top: 10px;

				uni-button {
					margin-right: 10px;
				}
			}

			.content-list {
				margin-top: 20px;
				height: calc(100vh - 440px);
				overflow-y: auto;
				.u-checkbox {
					display: flex;
					margin-bottom: 5px;
				}
			}

			.download-btn {
				position: fixed;
				width: 100%;
				bottom: 5%;
				display: flex;
				justify-content: center;

				uni-button {
					margin-right: 10px;
				}
			}
		}
	}
</style>